Imports Microsoft.Office.Interop.Outlook

Public Class MailManager
    Implements IMailManager
    Private ReadOnly _mailToWorkWith As MailItem
    Private ReadOnly _application As Application

    Public Sub New(ByVal application As Outlook.Application, ByVal mailToWorkWith As MailItem)
        If IsNothing(mailToWorkWith) Then
            Throw New ArgumentNullException("mailtoWorkWith")
        End If

        If IsNothing(application) Then
            Throw New ArgumentNullException("application")
        End If

        _Application = application
        _mailToWorkWith = mailToWorkWith
    End Sub

    Public Function TheEmailCanBeMovedToTheNewDestination(ByVal destination As MAPIFolder) As Boolean Implements IMailManager.TheEmailCanBeMovedToTheNewDestination
        Return Not (IsNothing(destination) OrElse destination.FolderPath = TryCast(_mailToWorkWith.Parent, MAPIFolder).FolderPath)
    End Function

    Public Sub MoveTo(ByVal destination As MAPIFolder) Implements IMailManager.MoveTo
        If TheEmailCanBeMovedToTheNewDestination(destination) Then
            _mailToWorkWith.Move(destination)
        End If
    End Sub

    Public Sub CopyTo(ByVal destination As MAPIFolder) Implements IMailManager.CopyTo
        If TheEmailCanBeMovedToTheNewDestination(destination) Then
            _mailToWorkWith.UnRead = False
            DirectCast(_mailToWorkWith.Copy, MailItem).Move(destination)
        End If
    End Sub

    Public Function GetFolderByContactName(ByVal rootFolder As MAPIFolder, ByVal searchPattern As String) As MAPIFolder
        For Each folder As MAPIFolder In rootFolder.Folders
            If folder.Name.IndexOf(searchPattern) <> -1 Then
                Return folder
            End If

            For Each subfolder As MAPIFolder In folder.Folders
                GetFolderByContactName(subfolder, searchPattern)
            Next
        Next
        Return Nothing
    End Function
End Class